package com.wuyou.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.wuyou.param.ExportSqlTableToWordParam;
import com.wuyou.param.ExportYapiTableToWordParam;
import com.wuyou.service.ExportSqlToWordService;
import com.wuyou.service.YapiService;
import com.wuyou.util.ExportUtil;
import lombok.AllArgsConstructor;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api")
@AllArgsConstructor
public class DocGenerateController {

    final private ExportSqlToWordService exportSqlToWordService;

    /**
     * 将数据库表生成表格导出至word文档中
     * @param param 入参，dbname
     * @return 结果
     */
    @PostMapping("/export/sql/word")
    public ResponseEntity<FileSystemResource> exportSqlToWord(@Valid @RequestBody ExportSqlTableToWordParam param){
        exportSqlToWordService.exportSqlToWord(param);
        File file = new File(ExportSqlToWordService.DOC_FILE);
        return getBody(file);
    }

    /**
     * 查询yapi的接口数据，然后导出word
     */
    @PostMapping("/export/yapi/word")
    public ResponseEntity<FileSystemResource> exportYapiWord(@Valid @RequestBody ExportYapiTableToWordParam param) {
        YapiService.pageTurning(10, 1, param.getProjectId(), param.getCookie(), param.getUrl());
        File file = new File(YapiService.DOC_FILE);
        return getBody(file);
    }

    private ResponseEntity<FileSystemResource> getBody(File file) {
        return ResponseEntity.ok()
                .header("Content-Disposition", "attachment; filename=" + file.getName())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(new FileSystemResource(file));
    }


    /**
     * 根据json导出excel
     *
     * @param array json数组，示例：[{"姓名":"张三","年龄":18},{"姓名":"李四","年龄":20}]，则会生成姓名年龄两列的excel
     */
    @PostMapping("/export/excel/by/json")
    public void exportExcelByJson(@Valid @RequestBody List<JSONObject> array, HttpServletResponse response) throws IOException {
        Workbook workbook = ExportUtil.generateExcelByJson(array);
        ExportUtil.downloadExcel(response, "byJson" + DateUtil.date().toString("yyyyMMddHHmmss") + ".xlsx", workbook);
    }


}
